package com.example.orderservice.service;

import com.example.orderservice.job.SendCouponAfter10s;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class QuartzService {
    @Autowired
    private Scheduler scheduler;

    public void start(String JobName, String cron) {
        JobDetail job = JobBuilder.newJob()
                .withIdentity(JobName)
                .ofType(SendCouponAfter10s.class).build();

        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(JobName)
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .build();

        try {
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public void stop(String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void restart(String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteJob(String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

}
